package com.shxy.controller;

import com.shxy.common.entity.CustomResult;
import com.shxy.common.enums.ResultCode;
import com.shxy.controller.ui.LoginData;
import com.shxy.controller.ui.UserInfo;
import com.shxy.entity.security.CustomUser;
import com.shxy.service.ISecurityService;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 安全管理控制器
 */
@RestController
@RequestMapping("/v1/security")
@Log
public class SecurityController {

    @Autowired
    private ISecurityService securityService;

    /**
     * 用户登录
     * @param loginData
     * @return
     */
    @PostMapping("/user/login")
    public CustomResult login(@RequestBody LoginData loginData) {
        Optional<CustomUser> pwd = securityService.checkLogin(loginData.getUsername(), loginData.getPassword(), loginData.getRole());
        if(pwd.isEmpty()) {
            return new CustomResult(ResultCode.USER_CREDENTIALS_ERROR);
        }

        // 构建返回结果
        Map<String,String> token = new HashMap<>() {{put("token", pwd.get().getCode());}};

        return new CustomResult(token);
    }

    /**
     * 查询用户信息
     * @param code
     * @return
     */
    @GetMapping("/user/info/{code}")
    public CustomResult<UserInfo> getUserInfo(@PathVariable(name = "code") String code) {
        // 根据编号获取用户信息
        Optional<UserInfo> userInfo = securityService.getUserInfoByCode(code);
        if(userInfo.isEmpty()) {
            return new CustomResult(ResultCode.PARAM_NOT_VALID);
        }
        userInfo.get().setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        return new CustomResult(userInfo);
    }

    /**
     * 用户登出
     * @return
     */
    @PostMapping("/user/logout")
    public CustomResult logout() {
        return new CustomResult("success");
    }
}
